import requests
import re
import os

headers = {
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cookie': 'BAIDUID=8A68063590088978933C646D8C5C182DFG=1; BIDUPSID=8A68063590088978933C646D8C5C182D; PSTM=1559310509; BDUSS=FTTFQ3QjMwbll4b3RjUHhSbjBZc0VqNVFreEd-cG03MzB0ejVxSG5Gb3B0QmxkSUFBQUFBJCQAAAAAAAAAAAEAAABE6YWiyb3Ex7HftcTK3dfTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACkn8lwpJ~Jcdj; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=1422_21112_29135_29237_28519_29099_29138_28830_28584_29133; from_lang_often=%5B%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%2C%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%5D; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; delPer=0; PSINO=6; locale=zh; to_lang_often=%5B%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%5D; yjs_js_security_passport=44d91f1c29084aec5a98dbf480fcbc8aeb92f3b4_1559742100_js',
    'origin': 'https://fanyi.baidu.com',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
}


def get_token_gtk():
    resp = requests.get(
        url='https://fanyi.baidu.com',
        headers=headers
    )

    content = resp.text

    token = re.search("token: '(.*?)'", content).group(1)
    window_dtk = re.search(";window.gtk = '(.*?)';", content).group(1)

    return token, window_dtk


def handle_js_file():
    token, gtk = get_token_gtk()
    with open('baidu_.js', 'r', encoding='utf-8') as f:
        js_ = f.read().replace("&&&", gtk)

    with open('baidu_', 'w', encoding='utf-8') as f:
        f.write(js_)

    sign = os.popen('node baidu_.js %s' % query).readlines()[0].strip()
    return sign, token


def translation_query(w):
    sign, token = handle_js_file()
    resp = requests.post(
        url='https://fanyi.baidu.com/v2transapi',
        data={
            'from': 'zh',
            'to': 'en',
            'query': query,
            'simple_means_flag': '3',
            'sign': sign,
            'token': token
        },
        headers=headers
    )

    json_result = resp.json()
    return json_result.get('trans_result').get('data')[0].get('result')[0][1]


if __name__ == '__main__':
    query = input("请输入需要翻译的内容 >")
    tran_result = translation_query(query)
    print(tran_result)
